package org.seeplnframework.skyeye.logback.api.listener;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import org.seeplnframework.skyeye.logback.api.layout.BusinessMDCPatternLogbackLayout;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

public class LoggingApplicationListener implements SpringApplicationRunListener {

    protected static final String LOGBACK_PATTERN = "[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%p] [%t] %c %L [%tid] [%B{app}] [%B{user}] [%B{space}] - %m%n";

    public LoggingApplicationListener(SpringApplication application, String[] args) {

    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
//        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
//        if (loggerContext == null){
//            return;
//        }
//        List<Logger> loggers = loggerContext.getLoggerList();
//        for(Logger logger : loggers){
//            Iterator<Appender<ILoggingEvent>> appenders = logger.iteratorForAppenders();
//            while(appenders.hasNext()){
//                Appender<ILoggingEvent> appender = appenders.next();
//                if(appender instanceof OutputStreamAppender){
//                    Encoder<ILoggingEvent> encoder = ((OutputStreamAppender<ILoggingEvent>)appender).getEncoder();
//                    if(encoder instanceof LayoutWrappingEncoder){
//                        BusinessMDCPatternLogbackLayout businessLayOut = new BusinessMDCPatternLogbackLayout();
//                        businessLayOut.setContext(loggerContext);
//                        businessLayOut.setPattern(LOGBACK_PATTERN);
//                        businessLayOut.start();
//                        Field field = ReflectionUtils.findField(encoder.getClass(), "layout");
//                        field.setAccessible(true);
//                        ReflectionUtils.setField(field, encoder, businessLayOut);
//                    }
//                }
//            }
//        }
    }

}
